/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jogs.client;

import java.io.*;
import java.net.*;

/**
 *
 * @author lanctot
 */
public class Main
{

    private boolean loggedIn;
    private LoginFrame loginFrame;
    private ClientFrame clientFrame;

    private Socket socket;
    private BufferedReader in;
    private PrintStream out; 
    private String username;

    static boolean nowindow = false;

    public static void main(String args[])
    {
      if (args.length == 2)
      {
        LoginFrame.arg_username = args[0];
        LoginFrame.arg_password = args[1];
        nowindow = true;
      }
      Main main = new Main();
      main.start();
    }

    public Main()
    {
      loggedIn = false;
      loginFrame = null;
    }

    /**
     * Inner class events.
     */
    public class LoginFrameThread implements Runnable
    {
      Main main;
      public LoginFrameThread(Main _m) { main = _m; }
      public void run() {
        main.loginFrame = new LoginFrame(main, main.nowindow);

        if (!nowindow)
          main.loginFrame.setVisible(true);
      }
    }

    public class ClientFrameThread implements Runnable
    {
      Main main;
      public ClientFrameThread(Main _m) { main = _m; }
      public void run() {
        main.clientFrame = new ClientFrame(main.socket, main.in, main.out, main.username);
        main.clientFrame.setVisible(true);
        main.clientFrame.clientLoop();
      }
    }

    /**
     * Methods
     */

    public synchronized void wakeup()
    {
      notify(); 
    }
    
    public synchronized void setLoggedIn(boolean _l)
    { loggedIn = _l; }

    public synchronized void set(LoginFrame _lf, Socket _s, BufferedReader _in, PrintStream _out, String _username)
    {
      loginFrame = _lf; 
      socket = _s;
      in = _in;
      out = _out;
      username = _username; 
    }

    public synchronized void dologin()
    {
      try
      {
        java.awt.EventQueue.invokeLater(new LoginFrameThread(this));

        while (!loggedIn)
          wait();
        
        loginFrame.setVisible(false); 
      }
      catch(Exception e)
      {
        e.printStackTrace();
      }
    }

    public synchronized void clientframe()
    {
      try
      {
        java.awt.EventQueue.invokeLater(new ClientFrameThread(this));
      }
      catch(Exception e)
      {
        e.printStackTrace();
      }
    }

    public void start()
    {
      System.out.println("Doing login..");
      dologin();
      System.out.println("Done login.");
      //clientframe();

      loginFrame.setVisible(false);
      loginFrame = null;

      clientFrame = new ClientFrame(socket, in, out, username);
      clientFrame.setVisible(true);
      clientFrame.clientLoop();
    }


   

}
